package com.ljm.sys.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljm.common.page.PageDto;
import com.ljm.security.util.UserUtil;
import com.ljm.service.BaseServiceImpl;
import com.ljm.sys.org.api.SysOrgApi;
import com.ljm.sys.org.dto.SysOrgDto;
import com.ljm.sys.org.dto.SysOrgUserDto;
import com.ljm.sys.org.entity.SysOrg;
import com.ljm.sys.org.entity.SysOrgApp;
import com.ljm.sys.org.mapper.SysOrgMapper;
import com.ljm.sys.org.service.ISysOrgAppService;
import com.ljm.sys.org.service.ISysOrgService;
import com.ljm.sys.org.service.ISysOrgUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 机构 服务实现类
 * </p>
 *
 * @author HuamingChen
 * @since 2020-10-20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysOrgServiceImpl extends BaseServiceImpl<SysOrgMapper, SysOrg>
        implements ISysOrgService, SysOrgApi {
    @Resource
    private ISysOrgUserService sysOrgUserService;
    @Resource
    private ISysOrgAppService sysOrgAppService;

    @Override
    public void saveData(SysOrgDto dto) {
        SysOrg po=new SysOrg();
        mapperFacade.map(dto,po);
        if(dto.getId()==null){
            po.setCreater(UserUtil.getLoginName());
            po.setCreateTime(LocalDateTime.now());
            String orgId=IdWorker.get32UUID();
            po.setOrgId(orgId);
            po.setStatus(0);
            //应用管理员
            SysOrgUserDto userInfo = dto.getUserInfo();
            userInfo.setAddress(dto.getAdderss());
            userInfo.setMobile(dto.getMobile());
            userInfo.setEmail(dto.getEmail());
            userInfo.setOrgId(orgId);
            String nickName=StringUtils.isNotEmpty(userInfo.getNickName())?userInfo.getNickName():dto.getOrgName();
            userInfo.setNickName(nickName);
            userInfo.setRealName(nickName);
            userInfo.setType("11");
        }else{
            po.setEditor(UserUtil.getLoginName());
            po.setEditTime(LocalDateTime.now());
        }
        //保存机构
        this.saveOrUpdate(po);
        //保存管理员
        sysOrgUserService.saveData(dto.getUserInfo());
        //保存机构拥有的应用
        this.saveOrgApp(po.getOrgId(),dto.getUserInfo().getRoles());
    }

    /**
     * 保存机构拥有的应用
     * @param orgApps 应用
     */
    private void saveOrgApp(String orgId, Set<String> orgApps){
        sysOrgAppService.remove(new LambdaQueryWrapper<SysOrgApp>().eq(SysOrgApp::getOrgId,orgId));
        if(CollectionUtils.isNotEmpty(orgApps)){
            List<SysOrgApp> list=new LinkedList<>();
            orgApps.forEach(orgApp->
                list.add(new SysOrgApp(UserUtil.getLoginName(), LocalDateTime.now(), Boolean.FALSE,orgId,orgApp))
            );
            sysOrgAppService.saveBatch(list);
        }
    }

    @Override
    public void deleteData(@NotNull Long id) {
        this.removeById(id);
    }

    @Override
    public SysOrgDto getDataById(Long id) {
        SysOrg po = this.getById(id);
        if(po!=null){
            SysOrgDto dto = mapperFacade.map(po, SysOrgDto.class);
            //查询机构管理员
            SysOrgUserDto orgAdminInfo = sysOrgUserService.getOrgAdminInfo(po.getOrgId());
            dto.setUserInfo(orgAdminInfo);
            return dto;
        }else{
            return null;
        }
    }

    @Override
    public PageDto<SysOrgDto> getDataByPage(String orgId, String orgName, String orgCode, Integer pageNo, Integer pageSize) {
        PageDto<SysOrgDto> pageDto=new PageDto<>(pageNo,pageSize);
        IPage<SysOrg> page=new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<SysOrg> wrapper=new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(orgId)){
            wrapper.eq(SysOrg::getOrgId,orgId);
        }
        if(StringUtils.isNotEmpty(orgName)){
            wrapper.eq(SysOrg::getOrgName,orgName);
        }
        if(StringUtils.isNotEmpty(orgCode)){
            wrapper.eq(SysOrg::getOrgCode,orgCode);
        }
        page = this.page(page, wrapper);
        if(page.getTotal()>0){
            pageDto.setTotal(page.getTotal());
            pageDto.setRecords(mapperFacade.mapAsList(page.getRecords(),SysOrgDto.class));
        }
        return pageDto;
    }

    @Override
    public Map<Class, Class> classMap() {
        Map<Class,Class> map=new HashMap<>(1);
        map.put(SysOrg.class,SysOrgDto.class);
        return map;
    }
}
